using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Prologis.ShifterNT.Filter
{

    public class StringMatchFilter : FilterSkeleton
    {


        bool acceptOnMatch = false;
        public bool AcceptOnMatch
        {
            get { return acceptOnMatch; }
            set { acceptOnMatch = value; }
        }


        string stringToMatch = null;
        public string StringToMatch
        {
            get { return stringToMatch; }
            set { stringToMatch = value; }
        }


        Regex regex = null;
        string regexToMatch;
        public string RegexToMatch
        {
            get { return regexToMatch; }
            set
            {
                regexToMatch = value;
                regex = new Regex(regexToMatch, RegexOptions.Compiled);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// 
        IList<string> fieldList = new List<string>();
        public void AddFieldName(string name)
        {
            fieldList.Add(name);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// 
        override public FilterDecision Decide(Object obj)
        {

            if (stringToMatch == null && regex == null)
            {
                return FilterDecision.Neutral;
            }

            string value = string.Empty;
            FieldList fields = (FieldList)obj;
            foreach (string field in fieldList)
            {
                value += fields[field].Value.ToString();
            }

            if (regex != null)
            {
                // Check the regex
                if (regex.Match(value).Success == false)
                {
                    // No match, continue processing
                    return FilterDecision.Neutral;
                }

                // we've got a match
                if (acceptOnMatch)
                {
                    return FilterDecision.Accept;
                }

                return FilterDecision.Deny;

            }
            else if (stringToMatch != null)
            {
                // Check substring match
                if (value.IndexOf(stringToMatch) == -1)
                {
                    // No match, continue processing
                    return FilterDecision.Neutral;
                }

                // we've got a match
                if (acceptOnMatch)
                {
                    return FilterDecision.Accept;
                }
                return FilterDecision.Deny;
            }

            return FilterDecision.Neutral;

        }
    }



}



